//
//  SongListViewModel.swift
//  TimMusic
//
//  Created by nkl on 2024/10/10.
//

import Foundation
import TSVideoKit
import UIKit

protocol BasicSongListViewModelProtocol: UITableViewDataSource {
    var datas: [TSVideo] { get set }
    func requestData()
}

class SongListViewModel: NSObject, BasicSongListViewModelProtocol {
    @Published var datas: [TSVideoKit.TSVideo] = []

    func requestData() {
        datas = TSVideoOperator.shared.dataManager.fetchAllVideos()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SongListCell.cellIdentify, for: indexPath) as! SongListCell
        if indexPath.row < datas.count {
            let video = datas[indexPath.row]
            cell.bindData(video: video)
        }
        cell.likeButtonAction = { mVideo in
            if mVideo.isFavorite {
                TSVideoOperator.shared.dataManager.dislikeVideo(video: mVideo) { _ in
                }
            } else {
                TSVideoOperator.shared.dataManager.likeVideo(video: mVideo) { _ in
                }
            }
        }
        return cell
    }


    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if indexPath.row < datas.count {
            let ac = UIAlertController(title: nil,
                                       message: "Are you sure to delete".localized(), preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel))
            ac.addAction(UIAlertAction(title: "Delete".localized(), style: .destructive, handler: { _ in

                let video = self.datas[indexPath.row]
                TSVideoOperator.shared.dataManager.deleteVideo(video: video) { _ in
                    NotificationCenter.default.post(name: kDataChangedNotifactionName, object: nil)
                }

            }))
            TMTabbarViewController.rootTabbar?.present(ac, animated: true)
        }
    }
}

class FavouriteViewModel: SongListViewModel {
    override func requestData() {
        datas = TSVideoOperator.shared.dataManager.fetchFavouriteVideos(sort: NSSortDescriptor(key: "createdAt", ascending: true))
    }
}

class RecentlyViewModel: SongListViewModel {
    override func requestData() {
        datas = TSVideoOperator.shared.dataManager.fetchAllVideos()
    }
}

class MostPlayedViewModel: SongListViewModel {
    override func requestData() {
        datas = TSVideoOperator.shared.dataManager.fetchAllVideos()
    }
}
